import traceback

from ..assistant import FwVariables
from robot.api import logger
import os

# 设置web_driver代理，拦截请求
proxy = None
server = None

try:
    from browsermobproxy import Server

    server = Server(FwVariables.ui_proxy_server_bin_path())
    server.start()
    proxy = server.create_proxy()
    logger.info('start http server proxy succeed {}'.format(proxy.proxy))
except:
    logger.error('start http server proxy failed')


def proxy_add_driver_options(options, url=None):
    if options is None:
        options = ''
    if is_app_env() or FwVariables.get_headless_mode():
        if type(options) == str:
            # add_argument_str = "add_argument(\'--no-sandbox\');add_argument(\'--disable-dev-shm-usage\');add_argument(\'--headless\');add_argument(\'--window-size=1920,1080\')"
            add_argument_str = "add_argument(\'--disable-gpu\');add_argument(\'--no-sandbox\');add_argument(\'--disable-dev-shm-usage\');add_argument(\'--headless\');add_argument(\'--window-size=1920,1080\')"
            if options:
                options = ";".join(list(set(add_argument_str.split(";") + options.split(";"))))
            else:
                options = add_argument_str
        else:
            try:
                options.add_argument("--headless")
                options.add_argument("--no-sandbox")
                options.add_argument("--disable-dev-shm-usage")
                options.add_argument("--disable-gpu")
                options.add_argument("--window-size=1920,1080")
            except Exception:
                logger.error(traceback.format_exc())
    if is_proxy_ui_request() and url and url.lower().startswith("http://"):
        if type(options) == str:
            if options is None or options == '' or options.isspace():
                return 'add_argument(\'--proxy-server={}\')'.format(proxy.proxy)
            return options + '; add_argument(\'--proxy-server={}\')'.format(proxy.proxy)
        else:
            try:
                options.add_argument("--proxy-server={}".format(proxy.proxy))
                return options
            except Exception as e:
                logger.error(traceback.format_exc())
    return options


def is_proxy_ui_request():
    """
    是否代理浏览器请求
    """
    return proxy and proxy.proxy and (FwVariables.is_open_itracing_code_cover_collector() or is_intercept_ui_request())


def is_intercept_ui_request():
    """
    是否拦截记录浏览器请求，用于对浏览器请求分析
    """
    return proxy and proxy.proxy and FwVariables.is_intercept_ui_request()


def proxy_add_header(headers: dict):
    if proxy is not None:
        logger.debug("add headers {}".format(headers))
        proxy.headers(headers)
    else:
        logger.debug('no proxy exist')


def proxy_close():
    try:
        if proxy is not None:
            proxy.close()
        if server is not None:
            server.stop()
    except:
        logger.warn("close proxy failed")


def new_har(ref, options):
    if proxy is not None:
        proxy.new_har(ref, options=options)


def get_har():
    if proxy is not None:
        return proxy.har


def is_app_env():
    APP_NOT_REQUIRED_DEVICE = os.getenv("APP_NOT_REQUIRED_DEVICE", "False")
    if APP_NOT_REQUIRED_DEVICE == "True":
        return False
    PROJECT_TYPE = os.getenv("PROJECT_TYPE")
    return PROJECT_TYPE == "5"


def get_remote_url():
    chrome_driver_port = os.getenv("CHROME_DRIVER_PORT")
    chrome_driver_port = chrome_driver_port if chrome_driver_port else "4444"
    return "http://localhost:{}".format(chrome_driver_port) if is_app_env() else False
